package net.ib.mtalk.receiver;

import net.ib.mtalk.constant.MTalkIntent;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.service.SelecterService;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * C2DM receiver of registration result or messages.
 * @author urunimi, Arngard
 *
 */
public class C2DMReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		//MTalkLogWriter.v("C2DMReceiver.onReceive() - STT");
		
		if (MTalkIntent.ACTION_C2DM_REGISTRATION.equals(intent.getAction())) {	// C2DM 등록에 성공한 시점에 호출됨.
			handleRegistration(context, intent);
		} else if (MTalkIntent.ACTION_C2DM_RECEIVE.equals(intent.getAction())) {	// C2DM에서 푸시 메시지가 왔을 때
			MTalkLogWriter.d("C2DMReceiver.onReceive() : push received");
			SelecterService.actionPush(context);//LocalService.actionStart(context);
		}

		//MTalkLogWriter.v("C2DMReceiver.onReceive() - END");
	}

	private void handleRegistration(Context context, Intent intent) {
		//MTalkLogWriter.v("C2DMReceiver.handleRegistration() - STT");

		if (intent.getStringExtra("error") != null) {
			MTalkLogWriter.d("C2DMReceiver.handleRegistration() : Registration failed, should try again later.");
		} else if (intent.getStringExtra("unregistered") != null) {
			MTalkLogWriter.d("C2DMReceiver.handleRegistration() : unregistration done, new messages from the authorized sender will be rejected.");
		} else if (intent.getStringExtra("registration_id") != null) {
			MTalkLogWriter.d("C2DMReceiver.handleRegistration() : Registration succeeded.");
			GlobalPreferences.setRegistrationId(intent.getStringExtra("registration_id"));	// Preference에 저장.
			// 이제 우리측 서버에 이걸 등록해야 한다. 이 과정은 로그인 후에 이루어져야 하므로 NetFlowControl에서 처리한다.
		}

		//MTalkLogWriter.v("C2DMReceiver.handleRegistration() - END");
	}
}